package com.lzx.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.lzx.api.CommonResult;
import com.lzx.dto.BrandDto;
import com.lzx.entity.Brand;
import com.lzx.service.BrandService;
import com.lzx.util.PageUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 品牌(Brand)表控制层
 *
 * @author makejava
 * @since 2021-03-05 09:50:45
 */
@RestController
@RequestMapping("brand")
public class BrandController {
    /**
     * 服务对象
     */
    @Resource
    private BrandService brandService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Brand selectOne(Integer id) {
        return this.brandService.queryById(id);
    }

    @GetMapping("/getAllByPage")
    public CommonResult getAllByPage(HttpServletRequest request) {
        String key = request.getParameter("key");
        String page = request.getParameter("page");
        String rows = request.getParameter("rows");
        List<Brand> resultList = null;
        if (BeanUtil.isNotEmpty(key)) {
            resultList = brandService.list(new QueryWrapper<Brand>().eq("name", key));
        } else {
            resultList = brandService.list();
            if (BeanUtil.isNotEmpty(page) && BeanUtil.isNotEmpty(rows)) {
                PageInfo<Brand> pageInfo = PageUtil.startPage(resultList, Integer.parseInt(page), Integer.parseInt(rows));
                return CommonResult.success(pageInfo);
            }
        }
        return CommonResult.success(resultList);
    }

    @GetMapping("list")
    public CommonResult list() {
        List<Brand> brandList = brandService.list();
        return CommonResult.success(brandList);
    }

    @GetMapping("/getByCate")
    public CommonResult<List<Brand>> getByCate(@RequestParam String cateId) {
        if (cateId != null) {
            List<Brand> brandList = brandService.getByCateId(Integer.valueOf(cateId));
            return CommonResult.success(brandList);
        }
        return CommonResult.failed();
    }

    @PostMapping("/saveOrUpdate")
    public CommonResult saveOrUpdate(@RequestBody BrandDto brandDto) {
        Boolean result = brandService.saveOrUpdate(brandDto);
        return CommonResult.success(result);
    }

    @PostMapping("deleteBrand")
    public CommonResult remove(Integer id) {
        if (BeanUtil.isEmpty(id)) {
            return CommonResult.failed("删除失败");
        }
        boolean re = brandService.deleteById(id);
        return CommonResult.success(re);
    }
}
